<template>
  <view class="edit_wrapper">
    <view class="edit_bg">
      <view class="edit_header">
        <view class="edit_title">编辑资料</view>
        <view class="edit_back" @tap="handleBack">返回</view>
      </view>
    </view>

    <view class="edit_form">
      <view class="form_item">
        <view class="form_label">头像</view>
        <image class="form_avatar" :src="form.avatar" mode="aspectFill"></image>
        <button class="upload_btn" @tap="chooseAvatar">更换头像</button>
      </view>

      <view class="form_item">
        <view class="form_label">背景图</view>
        <image class="form_background_img" :src="form.backgroundImg" mode="aspectFill"></image>
        <button class="upload_btn" @tap="chooseBackgroundImg">更换背景图</button>
      </view>

      <view class="form_item">
        <view class="form_label">昵称</view>
        <input class="form_input" v-model="form.nickname" placeholder="请输入昵称" />
      </view>

      <view class="form_item">
        <view class="form_label">个人介绍</view>
        <textarea class="form_textarea" v-model="form.introduction" placeholder="请输入个人介绍"></textarea>
      </view>

      <button class="submit_btn" @tap="handleSubmit">保存修改</button>
    </view>
  </view>
</template>

<script>
import { uploadFiles, updateUserInfo, getUserInfo } from '../../service/api.js';

export default {
  data() {
    return {
      form: {
        avatar: '',
        backgroundImg: '',
        nickname: '',
        introduction: ''
      },
      newAvatarPath: '',
      newBackgroundImgPath: ''
    };
  },
  // 文件：编辑页面的 <script> 部分
  onLoad() {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
      return;
    }

    getUserInfo().then((responseData) => { // responseData 为后端返回的 data 字段
      if (responseData) {
        this.form = {
          avatar: responseData.avatar,
          backgroundImg: responseData.backgroundImg,
          nickname: responseData.nickname,
          introduction: responseData.introduction
        };
        uni.setStorageSync('userInfo', responseData); // 存储最新数据
      }
    }).catch((err) => {
      console.error('获取用户信息失败:', err);
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        this.form = {
          avatar: userInfo.avatar,
          backgroundImg: userInfo.backgroundImg,
          nickname: userInfo.nickname,
          introduction: userInfo.introduction
        };
      }
    });
  },
  
  onShow() {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
    }
  },
  methods: {
    handleBack() {
      uni.navigateBack();
    },
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: async (res) => {
          this.newAvatarPath = res.tempFilePaths[0];
          const { avatarUrl } = await uploadFiles(this.newAvatarPath, null);
          this.form.avatar = avatarUrl;
        }
      });
    },
    chooseBackgroundImg() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: async (res) => {
          this.newBackgroundImgPath = res.tempFilePaths[0];
          const { backgroundImgUrl } = await uploadFiles(null, this.newBackgroundImgPath);
          this.form.backgroundImg = backgroundImgUrl;
        }
      });
    },
    handleSubmit() {
      // console.log('提交的用户信息:', JSON.stringify(this.form));
      updateUserInfo(this.form)
       .then((res) => {
          console.log('接口返回数据:', JSON.stringify(res));
          if (res && typeof res === 'object' && 'code' in res && res.code === 200) {
            uni.showToast({ title: res.msg || '操作成功', icon:'success' });
            uni.setStorageSync('userInfo', this.form);
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({ title: res.msg, icon: 'none' });
            // const errorMsg = res && res.msg? res.msg : '修改失败，未知错误';
            // console.error('接口返回错误:', errorMsg, '完整响应:', res);
            // uni.showToast({ title: errorMsg, icon: 'none' });
          }
        })
        .catch((err) => {
          console.error('请求发生错误:', err);
          const errorMsg = err && err.msg ? err.msg : '请求失败，未知错误';
          console.error('请求错误:', errorMsg, '完整错误:', err);
        });
      //  .catch((err) => {
      //     console.error('请求发生错误:', err);
      //     if (err.response) {
      //       console.error('状态码:', err.response.statusCode);
      //       console.error('响应数据:', err.response.data);
      //     } else if (err.request) {
      //       console.error('请求对象:', err.request);
      //     } else {
      //       console.error('错误信息:', err.message);
      //     }
      //     uni.showToast({ title: '请求发生错误，请稍后重试', icon: 'none' });
      //   });
    }
  }
};
</script>

<style>
.edit_wrapper {
  background: linear-gradient(135deg, rgba(170, 207, 252, 1) 0%, rgba(187, 208, 251, 1) 50%, rgba(178, 236, 248, 1) 100%);
  min-height: 100vh;
}

.edit_bg {
  background: #5983ff;
  height: 200rpx;
  border-bottom-left-radius: 60rpx;
  border-bottom-right-radius: 60rpx;
}

.edit_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 80rpx 30rpx 0 30rpx;
}

.edit_title {
  color: white;
  font-size: 36rpx;
  font-weight: bold;
}

.edit_back {
  color: white;
  font-size: 28rpx;
}

.edit_form {
  background: white;
  margin: 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.form_item {
  margin-bottom: 40rpx;
}

.form_label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.form_avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid #eee;
}

.form_background_img {
  width: 100%;
  height: 200rpx;
  border: 4rpx solid #eee;
}

.upload_btn {
  margin-top: 20rpx;
  background: #f5f5f5;
  color: #333;
  font-size: 24rpx;
  height: 60rpx;
  line-height: 60rpx;
  border-radius: 30rpx;
}

.form_input {
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.form_textarea {
  height: 200rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
}

.submit_btn {
  background: #5983ff;
  color: white;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  margin-top: 40rpx;
}
</style>